// var list = require('../../utils/list.js') 
import {
  getMerchantPickerList,
  submitOpenOrder
} from "../../../utils/networkRequest.js"
import {
  errorMsg
} from '../../../utils/tool.js'

//获取应用实例
const app = getApp()
Page({
  data: {

    duration: 500,
    content: '添加成功',
    $zanui: {
      toptips: {
        show: false
      }
    },
    // 左侧点击类样式
    curNav: '',
    submitArr: [], //要提交的检测项
    qcode: null,
    list: [],
    showCheckGoods: false, //是否显示选择商品的弹窗
    showShoppingCart: false, //是否显示展示购物车内容
    curCheckItem: null, //当前选择的项目
    shoppingCartArr: [], //购物车 
    timePrice: "", //工时费 
    qcode: "",
    isEdit: false, //是否是修改
    orderId: "", //订单id（如果是新建的订单就为空 如果是修改则是修改的订单id）

  },
  //弹出提示
  showTips() {
    this.setData({
      $zanui: {
        toptips: {
          show: true
        }
      }
    });

    setTimeout(() => {
      this.setData({
        $zanui: {
          toptips: {
            show: false
          }
        }
      });
    }, this.data.duration);
  },
  onLoad: function(options) {
    let self = this; 

    //获取分类列表
    getMerchantPickerList(options.user_id,(r) => {
      if (r.code == 0) {
        console.log(r) 
        if (options.shoppingCartArr) {


          let tempobj = JSON.parse(options.shoppingCartArr) 
          if (options.isEdit) {
            //修改订单
            self.setData({
              isEdit: true,
              orderId: tempobj.id,
              list: r.data,
              curNav: r.data[0].target,
              qcode: options.qcode,
              shoppingCartArr: tempobj.service_items,
              timePrice:tempobj.time_fee
            })
          }else{
            self.setData({
              list: r.data,
              curNav: r.data[0].target,
              qcode: options.qcode,
              shoppingCartArr: tempobj.service_items,
              timePrice:tempobj.time_fee
            })
          }
          
        } else {
          self.setData({
            list: r.data,
            curNav: r.data[0].target,
            qcode: options.qcode
          })
        }


        // app.globalData.itemList = r.data //将项目列表放入全局变量
      }
    })
  },
  //购物车内,数据数量编辑
  handleZanStepperChange(e) {
    const pIndex = e.target.dataset.pindex;
    const cIndex = e.target.dataset.cindex;
    const stepper = e.detail;
    this.setData({
      [`shoppingCartArr[${pIndex}].products[${cIndex}].count`]: stepper,
    });
  },
  //获取商品价格
  getPrice: function(e) {
    const pIndex = e.target.dataset.pindex;
    const cIndex = e.target.dataset.cindex;
    let oldPrice = [`shoppingCartArr[${pIndex}].products[${cIndex}].price`];
    debugger;
    this.setData({
      [`shoppingCartArr[${pIndex}].products[${cIndex}].price`]: e.detail.value,
    });
  },
  //获取工时费
  timePriceChange: function(e) {
    this.setData({
      timePrice: e.detail.detail.value
    })
  },
  onShow: function() {
    // if (app.globalData.itemList) {
    //   this.setData({
    //     list: app.globalData.itemList
    //   })
    // }
  },
 
  onReady: function() {


    var that = this;
    // 获取可视区高度
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          winHeight: res.windowHeight,
        })
      }
    })
  },


  //点击左侧 tab ，右侧列表相应位置联动 置顶
  switchRightTab: function(e) {
    var id = e.target.id;
    console.log(typeof id)
    this.setData({
      // 动态把获取到的 id 传给 scrollTopId
      scrollTopId: id,
      // 左侧点击类样式
      curNav: id
    })
  },
  //选择检测项
  onCheckItem: function(r) {
    let self = this;
    let {
      item
    } = r.currentTarget.dataset;
    if (item.has_product) {
      //选择的检测项目有商品
      self.setData({
        curCheckItem: item,
        showCheckGoods: true,
      })
    } else {
      //选择的检测项目没有商品  
      self.data.shoppingCartArr.push(item);
      self.setData({
        shoppingCartArr: self.data.shoppingCartArr,
      })
      wx.vibrateShort()
      self.showTips();
    }
  },
  //显示购物车
  showShoppingCart: function() {
    this.setData({
      showShoppingCart: true
    })
  },
  //关闭选择商品的弹窗
  onCheckGoodsClose: function() {
    this.setData({
      showCheckGoods: false,
    })

  },
  //关闭购物车的弹窗
  onShoppingCartClose: function() {
    this.setData({
      showShoppingCart: false
    })

  },
  //选择商品
  checkPro: function(r) {
    let {
      curCheckItem
    } = this.data;
    let curproid = r.currentTarget.dataset.curproid;
    curCheckItem.products.map((o, i) => {
      if (o.id == curproid) {
        o.isActive = !o.isActive;
      }
    })
    let curprice = 0;
    curCheckItem.products.map((o, i) => {
      o.count = 1;
      if (o.isActive) {
        curprice += o.price;
      }
    })

    curCheckItem.price = curprice;

    this.setData({
      curCheckItem: curCheckItem,

    })

  },
  //删除购物车中的项目
  delPro: function(e) {
    let self = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除这个项目吗？',
      success: function(res) {
        if (res.confirm) {
          let idx = e.currentTarget.dataset.idx
          self.data.shoppingCartArr.splice(idx, 1);
          self.setData({
            shoppingCartArr: self.data.shoppingCartArr
          })
        } else if (res.cancel) {
          //点击取消
        }
      }
    })

  },
  //选择商品点击确定
  onConfirm: function() {
    let total = 0;
    this.data.shoppingCartArr.push(
      this.data.curCheckItem
    )
    this.setData({
      shoppingCartArr: this.data.shoppingCartArr,
      showCheckGoods: false
    })
    wx.vibrateShort()
    this.showTips();
  },
  //确认开单项目
  addSubmitOrder: function() {
    let self = this;
    let {
      qcode,
      timePrice,
      orderId,
      isEdit
    } = this.data;
    let ordersArr = [];
    let carList = this.data.shoppingCartArr
    if (carList.length == 0) {
      wx.showToast({
        icon: "none",
        title: '请先添加项目',
      })
    } else {
      // carList.map((o, i) => {
      //   if (o.has_product) {
      //     //有子商品
      //     let curActivePros = [];
      //     o.products.map((oo, ii) => {
      //       if (oo.isActive) {
      //         curActivePros.push(oo);
      //       }
      //     })
      //     o.activeProducts = curActivePros;

      //     ordersArr.push({
      //       service_item_id: o.id,
      //       count: 1,
      //       money: o.price,
      //       products: o.activeProducts,
      //     })

      //   } else {
      //     //没有子商品
      //     ordersArr.push({
      //       service_item_id: o.id,
      //       count: o.products[0].count,
      //       money: o.products[0].price,
      //       products: [],
      //     })
      //   }
      // })


      submitOpenOrder(orderId, qcode, timePrice, carList, (r) => {
        if (r.code == 0) {
          if (isEdit){
            wx.navigateBack();
          }else{
            //确认订单
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 2]; //上一个页面 
            //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
            console.log(r.data.service_items)
            console.log("----------上面的是后端返回的数据 - 下面的是前端传给后端的数据 --------------")
            console.log(self.data.shoppingCartArr)

            prevPage.setData({
              orderInfo: r.data,
              shoppingCartArr: self.data.shoppingCartArr
            })
            wx.navigateBack();
          }
          
        }
      })
    }

  },




})